import type {HttpRequestConfig} from "luch-request";
import {getAccessToken, getTenantId} from "@/utils/auth";

/**
 * 请求前拦截器
 */
export const reqInter = (config: HttpRequestConfig): HttpRequestConfig => {
    loadingHandler(config) // 加载弹窗显示
    tokenHandler(config) // TOKEN 配置
    tenantHandler(config) // 租户配置
    return config
}

// Loading全局实例
const LoadingInstance = {target: null, count: 0};

/**
 * 显示 Loading
 */
function loadingHandler(config: HttpRequestConfig) {
    if (!config.custom?.showLoading) return
    LoadingInstance.count++;
    LoadingInstance.count === 1 &&
    uni.showLoading({
        title: config.custom?.loadingMsg,
        mask: true,
        fail: () => uni.hideLoading()
    });
}

/**
 * 关闭loading
 */
export function closeLoading() {
    if (LoadingInstance.count > 0) LoadingInstance.count--;
    if (LoadingInstance.count === 0) uni.hideLoading();
}


/**
 * Token 配置
 */
function tokenHandler(config: HttpRequestConfig) {
    let isToken = (config.header || {}).isToken === 'false'
    if (getAccessToken() && !isToken)
        config.header!.Authorization = `Bearer ${getAccessToken()}`
}

/**
 * 租户配置
 */
const tenantEnable = import.meta.env.VITE_APP_TENANT_ENABLE || true

function tenantHandler(config: HttpRequestConfig) {
    if (tenantEnable) config.header!['tenant-id'] = getTenantId() || 1
}
